﻿// asio网络编程--同步读写server示例.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include<boost/asio.hpp>
#include<memory>
#include<set>


const int max_length = 1024;
typedef std::shared_ptr<boost::asio::ip::tcp::socket> socket_ptr;
std::set<std::shared_ptr<std::thread>> thread_set;



void session(socket_ptr sock)
{
    for (;;) {
        char data[max_length];
        memset(data, '\0', max_length);
        boost::system::error_code error;
        size_t length = sock->read_some(boost::asio::buffer(data,max_length),error);
        if (error == boost::asio::error::eof) {
            std::cout << "connect closed by peer" << std::endl;
            break;
        }
        else if (error) {
            throw boost::system::system_error(error);
        }
        std::cout << "receive from " << sock->remote_endpoint().address().to_string() << std::endl;
        std::cout << "receive message is: " << data << std::endl;
        //回传给对方
        boost::asio::write(*sock,boost::asio::buffer(data,length));
        std::cout << "callback send" << std::endl;
    }
}

void server(boost::asio::io_context& io_context, unsigned short port) {
    boost::asio::ip::tcp::acceptor a(io_context, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(),port));
    for (;;) {
        socket_ptr socket(new boost::asio::ip::tcp::socket(io_context));
        a.accept(*socket);
        auto t = std::make_shared<std::thread>(session, socket);
        thread_set.insert(t);
    }

}

int main()
{
    try {
        boost::asio::io_context ioc;
        server(ioc, 8080);
        for (auto& t : thread_set) {
            t->join();
        }
    }
    catch (std::exception& e) {
        std::cout << "Exception: " << e.what() << std::endl;
    }

    return 0;
}
